<template>
  <div class="cont-main">
    <div class="menu-body common-content">
      <div class="top-search-bar">
        <el-form size="small" ref="queryForm" inline>
          <el-form-item label="">
            <el-input
                @input="search"
                placeholder="按名称查询"
                clearable
                v-model="searCh.vendorName"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button
                type="primary"
                icon="el-icon-search"
                @click="search()">搜索
            </el-button>
            <el-button
                type="primary"
                icon="el-icon-refresh-right"
                @click="searchGo0()"> 刷新
            </el-button>
            <el-button
                v-if="auth&&auth.add"
                size="small"
                type="primary"
                icon="el-icon-plus"
                @click="addRole()">新增
            </el-button>
          </el-form-item>
        </el-form>
      </div>

      <Table
          ref="table"
          :table-header="tableHeader"
          :tableData="tableData"
          :pg-total-num="total"
          :max-height="tableMaxHeight"
          @handleSizeChange="handleSizeChange"
          @handleCurrentChange="handleCurrentChange">
        <div slot="operation" slot-scope="row">
          <i class="el-icon-edit table-btn" @click="edi(row)" title="修改" v-if="auth&&auth.edit"></i>
          <i class="el-icon-share table-btn"
             @click="jur(row)"
             v-show="row.data.id != getuserVid" title="赋权"></i>
          <i class="el-icon-delete table-btn del" @click="del(row)" title="删除" v-if="auth&&auth.del"></i>
        </div>
      </Table>
    </div>

    <Dialog
        :addNewVisible="menuVisible"
        @closeDia="closeDia"
        width="550px"
        :center="true"
        :title="flag == 1 ? '厂家新增' : '厂家编辑'">
      <div slot="elform">
        <el-form
            :model="form"
            :rules="rules"
            ref="formName"
            size="small"
            label-width="100px">
          <el-row>
            <el-col :span="24">
              <el-form-item label="厂家名称" prop="vendorName">
                <el-input v-model="form.vendorName"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="厂家电话" prop="vendorPhone">
                <el-input v-model="form.vendorPhone"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="备注" class="bz">
                <el-input type="textarea" v-model="form.remarks"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button size="small" @click="closeDia">取 消</el-button>
          <el-button size="small" type="primary" @click="addroleBtn">确 定</el-button>
        </div>
      </div>
    </Dialog>

    <Dialog
        :addNewVisible="jurVisible"
        @closeDia="jurcloseDia"
        width="720px"
        :center="true"
        :title="'赋权'">
      <div slot="body">
        <el-tabs v-model="activeName" @tab-click="tabClick">
          <el-tab-pane label="组件赋权" name="sub">
            <el-transfer
                v-if="activeName == 'sub'"
                @change="jurChange"
                @right-check-change="rightCheckChange"
                v-model="JurValue"
                :data="jurdata"
                :titles="
                activeName == 'sub'
                  ? ['未赋权组件', '已赋权组件']
                  : ['未赋权应用', '已赋权应用']"></el-transfer>
            <div class="kzq">
              <span class="cfff">控制权：</span>
              <el-switch
                  v-model="isAuthority"
                  @change="swiChange"
                  active-color="#13ce66"
                  inactive-color="#ff4949">
              </el-switch>
            </div>
          </el-tab-pane>
          <el-tab-pane label="应用赋权" name="app">
            <el-transfer
                v-if="activeName == 'app'"
                @change="jurChange"
                @right-check-change="rightCheckChange"
                v-model="JurValue"
                :data="jurdata"
                :titles="
                activeName == 'sub'
                  ? ['未赋权组件', '已赋权组件']
                  : ['未赋权应用', '已赋权应用']"></el-transfer>
            <div class="kzq">
              <span class="cfff">控制权：</span>
              <el-switch
                  @change="swiChange"
                  v-model="isAuthority"
                  active-color="#13ce66"
                  inactive-color="#ff4949">
              </el-switch>
            </div>
          </el-tab-pane>
        </el-tabs>

        <div slot="footer" class="dialog-footer">
          <el-button @click="jurcloseDia">关 闭</el-button>
          <el-button type="primary" @click="juraddroleBtn">确 定</el-button>
        </div>
      </div>
    </Dialog>
  </div>
</template>

<script>
import Table from "@/components/Table";
import Dialog from "@/components/Dialog/Dialog";
import {
  get_vendorListByPage,
  post_addVendor,
  put_editVendor,
  del_delVendor,
  get_getLeftPv,
  get_getRightPv,
  put_addPv,
  get_getLeftAv,
  get_getRightAv,
  put_addAv,
} from "@/apis/user/userApi";
import {debounce} from '@/utils'
import {getCookie} from '@/utils/auth'

export default {
  aside: 'comp/CompAside',
  components: {Table, Dialog},
  data() {
    return {
      auth: null,
      tableMaxHeight: '50px',
      rules: {
        vendorPhone: [
          {required: true, message: "请输入厂家电话", trigger: "blur"},
        ],
        vendorName: [
          {required: true, message: "请输入厂家名称", trigger: "blur"},
        ],
      },
      searchData: {
        time: null,
        searchName: "",
        status: "",
        protocol: "",
      },
      dialogVisible: false,
      nowPage: 1,
      total: 0,
      currentPage: 1,
      pageSize: 10,
      detailForm: {},
      tableData: [],
      selectData: [],
      tableHeader: [
        {prop: "vendorName", name: "研究所名称", minWidth: 100},
        {prop: "vendorPhone", name: "研究所电话", minWidth: 100},
        {prop: "addTime", name: "新增时间", minWidth: 100},
        {prop: "editTime", name: "修改时间", minWidth: 100},
        {prop: "remarks", name: "备注", minWidth: 100},
        {prop: "operation", name: "操作", minWidth: 100, slot: true}
      ],
      menuVisible: false,
      flag: 1,
      form: {
        vendorName: "",
        vendorPhone: "",
        remarks: "",
      },
      searCh: {
        vendorName: "",
        vendorPhone: "",
      },
      //赋权
      jurVisible: false,
      JurValue: [],
      jurdata: [],
      isAuthority: false,
      vId: "",
      activeName: "sub",
      riSel: [],
      tJData: [],
    };
  },
  computed: {
    getuserVid() {
      return JSON.parse(getCookie("userInfo")).vendorId;
    }
  },
  created() {
    this.getList();
  },
  mounted() {
    this.$nextTick(() => {
      this.tableMaxHeight = window.innerHeight - this.$refs.table.$el.offsetTop - 50 - 30 - 48 + 'px'
    })
  },
  methods: {
    //点击切换
    tabClick(val, e) {
      this.JurValue = [];
      this.jurdata = [];
      this.riSel = [];
      this.tJData = [];
      if (val.name == "app") {
        this.getYY(this.vId);
      } else {
        this.getZjandYY(this.vId);
      }
    },
    rightCheckChange(val) {
      this.riSel = val;
    },
    swiChange(val) {
      if (this.riSel.length > 0) {
      } else {
        this.$message.warning("请先选择右侧需要赋权的选项");
        this.isAuthority = !val;
      }
    },
    //权限确定
    juraddroleBtn() {
      this.tJData = [];
      let arr = JSON.parse(JSON.stringify(this.JurValue));
      if (this.activeName == "sub") {
        if (this.riSel.length > 0) {
          this.riSel.forEach((item) => {
            this.JurValue.forEach((res) => {
              if (item == res) {
                this.tJData.push({
                  'pluginsId': res,
                  isAuthority: this.isAuthority ? "1" : "0",
                });
                arr.remove(res);
              }
            });
          });
          arr.forEach((item, index) => {
            this.tJData.push({
              'pluginsId': item,
              isAuthority: "0",
            });
          });
        } else {
          this.JurValue.forEach((res, index) => {
            this.tJData.push({
              isAuthority: "0",
              'pluginsId': res
            });
          });
        }
        let deleteA = []
        this.jurdata.forEach(item => {
          deleteA.push(item.key)
        })
        this.tJData.forEach(item => {
          deleteA.remove(item.pluginsId)
        })
        put_addPv({
          vendorId: this.vId,
          add: this.tJData,
          delete: deleteA
        }).then((res) => {
          console.log(res);
          let {code, msg} = res.data;
          this.$message.success(msg);
        });
      } else {
        if (this.riSel.length > 0) {
          this.riSel.forEach((item) => {
            this.JurValue.forEach((res) => {
              if (item == res) {
                this.tJData.push({
                  'appId': res,
                  isAuthority: this.isAuthority ? "1" : "0",
                });
                arr.remove(res);
              }
            });
          });
          arr.forEach((item, index) => {
            this.tJData.push({
              'appId': item,
              isAuthority: "0",
            });
          });
        } else {
          this.JurValue.forEach((res, index) => {
            this.tJData.push({
              isAuthority: "0",
              'appId': res
            });
          });
        }
        let deleteA = []
        this.jurdata.forEach(item => {
          deleteA.push(item.key)
        })
        this.tJData.forEach(item => {
          deleteA.remove(item.appId)
        })

        put_addAv({
          vendorId: this.vId,
          add: this.tJData,
          delete: deleteA
        }).then((res) => {
          console.log(res);
          let {code, msg} = res.data;
          if (code == 0) {
            this.$message.success(msg);
          }
        });
      }
    },
    //获取组件与应用列表
    getZjandYY(vendorId) {
      get_getLeftPv({vendorId}).then((res) => {
        let {data} = res.data;
        data.forEach((item) => {
          this.jurdata.push({
            key: item.id,
            label: item.pluginsName,
          });
        });
      });
      get_getRightPv({vendorId}).then((res) => {
        let {data} = res.data;
        data.forEach((item) => {
          this.jurdata.push({
            key: item.id,
            label: item.pluginsName,
          });
          this.JurValue.push(item.id);
        });
      });
    },
    getYY(vendorId) {
      get_getLeftAv({vendorId}).then((res) => {
        let {data} = res.data;
        data.forEach((item) => {
          this.jurdata.push({
            key: item.id,
            label: item.appName,
          });
        });
      });
      get_getRightAv({vendorId}).then((res) => {
        let {data} = res.data;
        data.forEach((item) => {
          this.jurdata.push({
            key: item.id,
            label: item.appName,
          });
          this.JurValue.push(item.id);
        });
      });
    },
    jurChange(val) {
      this.riSel = [];
      if (!this.JurValue.label > 0) {
        this.isAuthority = false
      }
    },
    jur({data}) {
      this.jurdata = [];
      this.JurValue = [];
      this.riSel = [];
      this.tJData = [];
      this.jurVisible = true;
      this.vId = data.id;
      if (this.activeName == "app") {
        this.getYY(data.id);
      } else {
        this.getZjandYY(data.id);
      }
    },
    //赋权弹框关闭
    jurcloseDia() {
      this.jurVisible = false;
      this.JurValue = [];
      this.jurdata = [];
    },
    //搜索
    search: debounce(function () {
      let tiem = {};
      for (const key in this.searCh) {
        if (this.searCh[key] != "") {
          tiem[key] = this.searCh[key];
        }
      }
      this.getList(tiem);
    }),
    searchGo0() {
      this.getList();
      this.searCh = {
        roleEnName: "",
        roleChName: "",
      };
    },

    //编辑
    edi(row) {
      this.flag = 2;
      this.menuVisible = true;
      this.form = {
        vendorName: row.data.vendorName,
        vendorPhone: row.data.vendorPhone,
        remarks: row.data.remarks,
        id: row.data.id,
      };
    },
    //删除
    del(row) {
      this.$confirm("此操作将永久删除该角色, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        del_delVendor({id: row.data.id}).then((res) => {
          let {code, msg} = res.data;
          this.$message.success(msg);
          this.getList();
        });
      }).catch(() => {

      });
    },
    //添加
    addRole() {
      this.flag = 1;
      this.menuVisible = true;
    },
    //弹框确认
    addroleBtn() {
      this.$refs["formName"].validate((valid) => {
        if (valid) {
          if (this.flag == 1) {
            post_addVendor(this.form).then((res) => {
              let {msg} = res.data;
              this.$message.success(msg);
              this.clearForm();
              this.getList();
            });
          } else {
            put_editVendor(this.form).then((res) => {
              let {msg} = res.data;
              this.$message.success(msg);
              this.clearForm();
              this.getList();
            });
          }
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    //获取列表
    getList(val = {}) {
      get_vendorListByPage(
        Object.assign({}, val, {
          pageSize: this.pageSize,
          pageNum: this.nowPage,
          menuId: this.$route.meta.id
        })
      ).then((res) => {
        // console.log(res);
        let {records, total} = res.data.data;
        this.auth = res.data.auth
        if (records.length === 0 && this.nowPage > 1) {
          this.nowPage--;
          this.getList();
        }
        this.total = total;
        records.forEach((item) => {
          if (item.addTime) {
            item.addTime = this.$moment(item.addTime).format(
              "YYYY-MM-DD HH:mm:ss"
            );
          }
          if (item.editTime) {
            item.editTime = this.$moment(item.editTime).format(
              "YYYY-MM-DD HH:mm:ss"
            );
          }
        });
        this.tableData = records;
      });
    },

    //关闭弹框
    closeDia() {
      this.menuVisible = false;
      this.clearForm();
    },
    clearForm() {
      this.menuVisible = false;
      if (this.$refs["formName"]) {
        this.$refs["formName"].resetFields();
      }
      this.form = {
        vendorName: "",
        vendorPhone: "",
        remarks: "",
      };
    },

    handleSizeChange(val) {
      this.pageSize = val;
      this.getList();
    },

    handleCurrentChange(val) {
      this.nowPage = val;
      this.getList();
    }
  },
};
</script>
<style lang="less" scoped>
  .cont-main {
    height: 100%;
    padding: 15px;

    .menu-body {
      height: 100%;
      padding: 15px;
    }
  }

  .kzq {
    display: flex;
    justify-content: center;
    margin: 20px;
  }

  .el-transfer {
    display: flex;
    justify-content: center;
    align-items: center;
  }

  /deep/ .el-tabs__item:not(.is-active) {
    color: #fff;
  }
</style>
